package cn.iocoder.yudao.module.system.controller.app.partnercoupon;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import cn.iocoder.yudao.module.promotion.api.coupon.CouponTemplateApi;
import cn.iocoder.yudao.module.promotion.api.coupon.dto.CouponTemplateRespDTO;
import cn.iocoder.yudao.module.promotion.enums.coupon.CouponStatusEnum;
import cn.iocoder.yudao.module.system.controller.admin.partner.vo.PartnerPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.partnercoupon.vo.PartnerCouponPageReqVO;
import cn.iocoder.yudao.module.system.controller.app.partnercoupon.vo.AppPartnerCouponRespVO;
import cn.iocoder.yudao.module.system.controller.app.partnercoupon.vo.AppPartnerCouponTakeReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.partner.PartnerDO;
import cn.iocoder.yudao.module.system.dal.dataobject.partnercoupon.PartnerCouponDO;
import cn.iocoder.yudao.module.system.service.partner.PartnerService;
import cn.iocoder.yudao.module.system.service.partnercoupon.PartnerCouponService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "用户 APP - 合伙人优惠券")
@RestController
@RequestMapping("/system/partnercoupon")
@Validated
public class AppPartnerCouponController {

    @Resource
    private MemberUserApi memberUserApi;
    @Resource
    private CouponTemplateApi couponTemplateApi;
    @Resource
    private PartnerService partnerService;

    @Resource
    private PartnerCouponService partnerCouponService;

    @GetMapping("/get")
    @Operation(summary = "获得合伙人优惠券详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<AppPartnerCouponRespVO> getPartnerCoupon(@RequestParam("id") Long id) {
        PartnerCouponDO partnerCoupon = partnerCouponService.getPartnerCoupon(id);
        AppPartnerCouponRespVO couponRespVO = BeanUtils.toBean(partnerCoupon, AppPartnerCouponRespVO.class);
        List<CouponTemplateRespDTO> couponTemplateList = couponTemplateApi.getCouponTemplateList(Arrays.asList(partnerCoupon.getTemplateId()));
        Map<Long, CouponTemplateRespDTO> couponTemplateMap = couponTemplateList.stream().collect(Collectors.toMap(CouponTemplateRespDTO::getId, item -> item));
        
        CouponTemplateRespDTO couponTemplateRespDTO = couponTemplateMap.get(couponRespVO.getTemplateId());
        BeanUtil.copyProperties(couponTemplateRespDTO, couponRespVO, new String[]{"id", "status"});

        couponRespVO.setCanTake(partnerCouponService.checkCanTake(id, getLoginUserId()));
        couponRespVO.setValidStartTime(partnerCoupon.getStartTime());
        couponRespVO.setValidEndTime(partnerCoupon.getEndTime());
        return success(couponRespVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得合伙人优惠券分页")
    public CommonResult<PageResult<AppPartnerCouponRespVO>> getPartnerCouponPage(@Valid PartnerCouponPageReqVO pageReqVO) {
        MemberUserRespDTO user = memberUserApi.getUser(getLoginUserId());
        PartnerPageReqVO partnerPageReqVO = new PartnerPageReqVO();
        partnerPageReqVO.setPhone(user.getMobile());
        List<PartnerDO> partnerList = partnerService.getList(partnerPageReqVO);
        if (CollectionUtils.isAnyEmpty(partnerList)) {
            return success(PageResult.empty());
        } else {
            pageReqVO.setPartnerId(partnerList.get(0).getId());
            pageReqVO.setNowTime(LocalDateTime.now());
            PageResult<PartnerCouponDO> pageResult = partnerCouponService.getPartnerCouponPage(pageReqVO);
            PageResult<AppPartnerCouponRespVO> pageResultVO = BeanUtils.toBean(pageResult, AppPartnerCouponRespVO.class);
            if (!CollectionUtils.isAnyEmpty(pageResultVO.getList())) {
                List<Long> templateIds = pageResultVO.getList().stream().filter(item -> Objects.nonNull(item.getTemplateId()))
                        .map(AppPartnerCouponRespVO::getTemplateId).collect(Collectors.toList());
                List<CouponTemplateRespDTO> couponTemplateList = couponTemplateApi.getCouponTemplateList(templateIds);
                Map<Long, CouponTemplateRespDTO> couponTemplateMap = couponTemplateList.stream().collect(Collectors.toMap(CouponTemplateRespDTO::getId, item -> item));
                pageResultVO.getList().forEach(item -> {
                    CouponTemplateRespDTO couponTemplateRespDTO = couponTemplateMap.get(item.getTemplateId());
                    BeanUtil.copyProperties(couponTemplateRespDTO, item, new String[]{"id", "status"});
                    item.setRemainCount(item.getTotalCount()-item.getTakeCount());
                    item.setValidStartTime(item.getStartTime());
                    item.setValidEndTime(item.getEndTime());
//                    LocalDateTime nowTime = LocalDateTime.now();
//                    if (!(nowTime.isAfter(item.getStartTime()) && nowTime.isBefore(item.getEndTime()))) {
//                        item.setStatus(CouponStatusEnum.EXPIRE.getStatus());
//                    }
                    item.setCanTake(item.getTakeCount() < item.getTotalCount());
                });
            }
            return success(pageResultVO);

        }
    }

    @PostMapping("/take")
    @Operation(summary = "合伙人优惠券领取")
    public CommonResult<Boolean> takPartnerCoupon(@Valid @RequestBody AppPartnerCouponTakeReqVO reqVO) {
        // 1. 领取优惠劵
        partnerCouponService.takPartnerCoupon(reqVO.getId(), getLoginUserId());
        // 2. 检查是否可以继续分享
        return success(partnerCouponService.checkCanTake(reqVO.getId(), getLoginUserId()));
    }
}